package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net"
	"os"
	"path/filepath"
	"strings"
)

func GetEthernetInfo() (string, error) {
	// 获取本机的网卡设备名
	hostname, err := os.Hostname()
	if err != nil {
		return "", fmt.Errorf("failed to get hostname: %v", err)
	}

	// 查找以太网接口
	interfaceName, macAddress, err := findEthernetInterface()
	if err != nil {
		return "", fmt.Errorf("failed to find Ethernet interface: %v", err)
	}

	// 读取速度文件
	filePath := filepath.Join("/sys/class/net", interfaceName, "speed")
	speedBytes, err := ioutil.ReadFile(filePath)
	if err != nil {
		return "", fmt.Errorf("failed to read speed file: %v", err)
	}

	// 转换速度为字符串
	speed := strings.TrimSpace(string(speedBytes))

	// 返回以太网口的信息
	return fmt.Sprintf("Hostname: %s\nInterface: %s\nMAC Address: %s\nSpeed: %s Mbps", hostname, interfaceName, macAddress, speed), nil
}

func findEthernetInterface() (string, string, error) {
	// 获取所有网络接口
	interfaces, err := net.Interfaces()
	if err != nil {
		return "", "", fmt.Errorf("failed to get network interfaces: %v", err)
	}

	// 遍历网络接口，找到以太网接口
	for _, iface := range interfaces {
		// 排除非以太网接口
		if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 {
			continue
		}

		// 判断是否为以太网接口
		if strings.HasPrefix(iface.Name, "eth") || strings.HasPrefix(iface.Name, "en") {
			return iface.Name, iface.HardwareAddr.String(), nil
		}
	}

	return "", "", fmt.Errorf("no Ethernet interface found")
}

func main() {
	ethernetInfo, err := GetEthernetInfo()
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(ethernetInfo)
}
